package com.albon.soccer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;

import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.albon.alarm.SoccerSetAlarm;
import com.albon.soccer.SoccerParser;
import com.albon.soccer.SoccerLeague;
import com.albon.sportsalarm.R;
import com.albon.util.Logg;
import com.albon.util.Schedule_Calendar;






public class SoccerLeague extends Activity implements OnClickListener {
	private final String TAG = "Premier_League";
	private SoccerParser sParser;
	private ListView listView;
	
    private SoccerAdapter mSoccerAdapter;
	private ArrayList<HashMap<String, String>> data;
	private ArrayList<Soccer> soccerArrayList;
	
	private TextView titleText;
	private TextView monthText;
	private Button monthPrevious;
    private Button monthNext;
    
    //private Calendar now = null;
    private String mYear; //올해
    private String mMonth; //이번달 
    
    private Schedule_Calendar sc;
    
    private String league_title = "";
    private String league_name = "";
    private int world = 0;
    
    private DatabaseHelper mDBHelper = null;
    private SQLiteDatabase db = null;
    
    private void init(){
    	titleText = (TextView)findViewById(R.id.title);
    	titleText.setText(league_title);
    	monthText = (TextView)findViewById(R.id.monthText);
    	monthPrevious = (Button)findViewById(R.id.monthPrevious);
    	monthPrevious.setOnClickListener(this);
    	monthNext = (Button)findViewById(R.id.monthNext);
    	monthNext.setOnClickListener(this);    	    	
    }
	
	private final Handler handler = new Handler() {
		public void handleMessage(Message msg) {		
			
			//Logg.d(TAG, "data size : "+data.size());
			 soccerArrayList = new ArrayList<Soccer>();
			for(int i=0;i<data.size();i++){
				//Logg.d(TAG, "data "+data.get(i).size());
				if(data.get(i).size()!=0){
					//Logg.d(TAG, ""+data.get(i).get("real_date")+ " // "+data.get(i).get("real_time")+  " // "+ data.get(i).get("a_team")+  " // "+ data.get(i).get("b_team")+  " // "+ data.get(i).get("score"));
					Soccer soccer = new Soccer(i, league_title, data.get(i).get("enable"), data.get(i).get("real_date"), data.get(i).get("real_time"), data.get(i).get("compare_date"), data.get(i).get("a_team"), data.get(i).get("b_team"), data.get(i).get("score"), data.get(i).get("notification"), data.get(i).get("stadium"), data.get(i).get("reague"));
					soccer.setBtnClicked(Boolean.valueOf(data.get(i).get("enable")));
					soccer.setmYear(mYear);
					soccer.setmMonth(mMonth);
					soccerArrayList.add(soccer);					
				}				
				
			}
			
			listViewUpdate();
		}
	};
	
	private void listViewUpdate() {
		
		mSoccerAdapter = new SoccerAdapter(this, R.layout.sports_item_row, soccerArrayList);
		mSoccerAdapter.notifyDataSetChanged();
		listView.setAdapter(mSoccerAdapter);
		//listView.setOnTouchListener(mOnTouchListener);
		listView.setOnItemClickListener(alarmOnItemClickListener);
	}

	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		final Window win = getWindow();
        win.requestFeature(Window.FEATURE_NO_TITLE);
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON );
		setContentView(R.layout.soccer_league);
		league_title = getIntent().getStringExtra("league_title");
		league_name = getIntent().getStringExtra("league_name");
		world = getIntent().getIntExtra("world", 0); //해외인지 국내인지 판단 0은 해외 1은 국내
		/*****************************************
		 * 안드로이드 3.0 이상 부터 네트웍 통신시 android.os.NetworkOnMainThreadException 에러 발생
		 * onCreate메소드 안에 StrictMode를 추가
		 * 참고 http://android-developers.blogspot.kr/2010/12/new-gingerbread-api-strictmode.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+blogspot/hsDu+(Android+Developers+Blog) 
		 *****************************************/		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()          
		.detectDiskWrites()
		.detectNetwork()              
		.penaltyLog().build());   
		
		 mDBHelper = new DatabaseHelper(this, DatabaseHelper.DATABASE_NAME);
	        if(db == null){        	
	        	db = mDBHelper.getWritableDatabase(); 
			}
	        
		data = new ArrayList<HashMap<String, String>>();
		
		
		listView = (ListView)findViewById(R.id.listView1);
		
		init();
		//sParse = new SoccerParse(Soccer_League.this, handler, data, mYear, mMonth, league_name);
		//sParse.parser();		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
				
		switch (v.getId()) {
		case R.id.monthPrevious:
			sc.setPreviousMonth();
			setMonthText();
			break;
		case R.id.monthNext:
			sc.setNextMonth();
			setMonthText();
			break;

		}
		//sParse.parser();
	}

    float xpos= 0.0f;
    
	View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				//Log.d(TAG, "event.getAction() : "+event.getAction());
				switch (event.getAction()) {
				case android.view.MotionEvent.ACTION_UP:	
					//Log.d(TAG, "event.getX()2 : "+event.getX()); 
					if(xpos>event.getX()){ //좌로 터치
					    if((xpos-event.getX())>250.0f){
					    	 sc.setNextMonth();				             
				 			 setMonthText();
					    }
					}
					if(xpos<event.getX()){//우로 터치
						if((event.getX()-xpos)>250.0f){							
							 sc.setPreviousMonth(); 
			                setMonthText();
						}
					}
					break;
				case android.view.MotionEvent.ACTION_DOWN:	
					//Log.d(TAG, "event.getX()1 : "+event.getX()); 
					xpos = event.getX();
					
					break;
				
				}
				return false;
			}
		};
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sc = new Schedule_Calendar();
    	setMonthText();
	}		
	
	private void setMonthText() {
        mYear = sc.getCurYear();
        mMonth = sc.getCurMonth();
		 Logg.d(TAG, "mYear : "+mYear);
		 Logg.d(TAG, "mMonth : "+mMonth);
		 monthText.setText(mYear+"."+mMonth);
		 sParser = null;
		 sParser = new SoccerParser(SoccerLeague.this, handler, data, world, mYear, mMonth, league_name);
		 sParser.parser();		
    }
	
	//클릭이벤트
		AdapterView.OnItemClickListener alarmOnItemClickListener = new AdapterView.OnItemClickListener(){

			public void onItemClick(AdapterView parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				Soccer soccer = (Soccer) view.getTag();
				Log.d(TAG, "onClick id : "+id+", view id = "+soccer.getId());
				Log.d(TAG, "onClick id : "+id+", soccer.getScore() = "+soccer.getScore());
				if(soccer.getScore().equals("")){ // 스코어가 없는것만 알람 설정할수 있도록
					Intent set_alarm_intent = new Intent(SoccerLeague.this, SoccerSetAlarm.class);
					set_alarm_intent.putExtra("league_title", league_title);
					set_alarm_intent.putExtra("compare_date", soccer.getCompare_date());
					set_alarm_intent.putExtra("a_team", soccer.getA_team());
					set_alarm_intent.putExtra("b_team", soccer.getB_team());
					set_alarm_intent.putExtra("real_date", soccer.getReal_date());
					set_alarm_intent.putExtra("real_time", soccer.getReal_time());
					set_alarm_intent.putExtra("year", mYear);
					set_alarm_intent.putExtra("month", mMonth);
					set_alarm_intent.putExtra("stadium", soccer.getStadium());
					
					startActivity(set_alarm_intent);
				}else{
					Toast.makeText(SoccerLeague.this, R.string.past_game, Toast.LENGTH_SHORT).show();
				}
			}
			
		};
		
}
